// pages/api/user/info.ts
import { NextApiRequest, NextApiResponse } from 'next';
import jwt from 'jsonwebtoken';
import prisma from '../../../lib/prisma';

interface JwtPayload {
  id: string;
  UserId: string;
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    const token = req.headers.authorization?.split(' ')[1];

    if (!token) {
      return res.status(401).json({ message: '未提供 Token' });
    }

    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as JwtPayload;
      const user = await prisma.user.findUnique({ where: { id: parseInt(decoded.id) }, select: { id: true, userId: true } });

      if (user) {
        return res.status(200).json(user);
      } else {
        return res.status(404).json({ message: '用户未找到' });
      }
    } catch (error) {
      console.error('Token 或数据库错误:', error);
      return res.status(500).json({ message: '内部服务器错误' });
    }
  } else {
    res.setHeader('Allow', ['GET']);
    res.status(405).end(`不允许的方法: ${req.method}`);
  }
}
